//
//  SHForumViewController.m
//  UI_CarHome
//
//  Created by dllo on 15/10/21.
//  Copyright (c) 2015年 沈浩. All rights reserved.
//

#import "SHForumViewController.h"
#import "SHNewslistCell.h"
#import "SHHandle.h"
#import "SHModel.h"
#import "SHDetailViewController.h"
#import "SHForumCollectionCell.h"
#import "SHHeaderCollectionCell.h"
@interface SHForumViewController ()<UITableViewDataSource, UITableViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate, UIScrollViewDelegate>

@property(nonatomic, retain)MBProgressHUD *hud;
@property(nonatomic, retain)NSString *lasttimeStr;
@property(nonatomic, assign)NSInteger page;

@property(nonatomic, retain)UITableView *northChinaTableView;
@property(nonatomic, retain)UITableView *centerChinaTableView;
@property(nonatomic, retain)UITableView *eastChinaTableView;

@property(nonatomic, retain)UICollectionView *collectionView;
// 数组
@property(nonatomic, retain)NSMutableArray *northChinaArr;
@property(nonatomic, retain)NSMutableArray *centerChinaArr;
@property(nonatomic, retain)NSMutableArray *eastChinaArr;
@property(nonatomic, copy)NSString *url;

@property(nonatomic, retain)UICollectionView *headCollectionView;
@property(nonatomic, retain)UICollectionViewFlowLayout *headFlowLayout;

@property(nonatomic, assign)NSInteger selectCount;

@end

@implementation SHForumViewController

- (void)dealloc
{
    [_hud release];
    [_lasttimeStr release];
    [_northChinaTableView release];
    [_centerChinaTableView release];
    [_eastChinaTableView release];
    [_collectionView release];
    [_northChinaArr release];
    [_centerChinaArr release];
    [_eastChinaArr release];
    [_url release];
    [_headCollectionView release];
    [_headFlowLayout release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self createBottomCollectionView];
    [self createHeadCollectionView];
//    self.navigationController.navigationBar.backgroundColor = [UIColor lightGrayColor];
    self.navigationController.navigationBar.translucent = NO;

    self.view.backgroundColor = BACKGROUNDCOLOR;
    self.northChinaTableView.backgroundColor = BACKGROUNDCOLOR;
    self.centerChinaTableView.backgroundColor = BACKGROUNDCOLOR;
    self.eastChinaTableView.backgroundColor = BACKGROUNDCOLOR;
    self.northChinaTableView.separatorStyle = SEPARATORSTYLE;
    self.centerChinaTableView.separatorStyle = SEPARATORSTYLE;
    self.eastChinaTableView.separatorStyle = SEPARATORSTYLE;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(isNight:) name:@"isNight" object:nil];
   

    
    [self createHud];
    [self createNorthChinaData];
    [self createHeaderAndFooter];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"sousuo.png"] style:UIBarButtonItemStylePlain target:self action:@selector(searchAction:)];
    
}
#pragma mark -- 夜间模式
- (void)isNight:(NSNotification *)notification {
    [self.northChinaTableView reloadData];
    [self.centerChinaTableView reloadData];
    [self.eastChinaTableView reloadData];
    [self.headCollectionView reloadData];
    self.view.backgroundColor = BACKGROUNDCOLOR;
    self.northChinaTableView.backgroundColor = BACKGROUNDCOLOR;
    self.centerChinaTableView.backgroundColor = BACKGROUNDCOLOR;
    self.eastChinaTableView.backgroundColor = BACKGROUNDCOLOR;
    self.northChinaTableView.separatorStyle = SEPARATORSTYLE;
    self.centerChinaTableView.separatorStyle = SEPARATORSTYLE;
    self.eastChinaTableView.separatorStyle = SEPARATORSTYLE;
    self.headCollectionView.backgroundColor = HEADERBACKCOLOR;
}

- (void)searchAction:(UIBarButtonItem *)button {
    SHSearchViewController *search = [[SHSearchViewController alloc] init];
    [self.navigationController pushViewController:search animated:YES];
    [search release];
}





#pragma mark --顶层collectionView
- (void) createHeadCollectionView {
    self.headFlowLayout = [[UICollectionViewFlowLayout alloc] init];
    self.headFlowLayout.itemSize = CGSizeMake(100, 35);
    self.headFlowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;

    
    self.headCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 35) collectionViewLayout:self.headFlowLayout];
    [self.view addSubview:self.headCollectionView];
    self.headCollectionView.dataSource = self;
    self.headCollectionView.delegate = self;
    self.headCollectionView.bounces = NO;
    [self.headCollectionView registerClass:[SHHeaderCollectionCell class] forCellWithReuseIdentifier:@"headerCollection"];
    self.headCollectionView.backgroundColor = HEADERBACKCOLOR;
    [_headCollectionView release];
    
}



#pragma mark --
- (void)createHeaderAndFooter {
    // 下拉刷新
    self.northChinaTableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(header)];
    self.centerChinaTableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(header)];
    self.eastChinaTableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(header)];
    // 上拉加载
    self.northChinaTableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footer)];
    self.centerChinaTableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footer)];
    self.eastChinaTableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footer)];
    
}

#pragma mark --
// 下拉刷新
- (void)header
{
    if (self.northChinaTableView) {
        [self createNorthChinaData];
        [self.northChinaTableView.header endRefreshing];
    } else if (self.centerChinaTableView) {
        [self createCenterChinaData];
    } else {
        [self createEastChinaData];
    }

}
#pragma mark --上拉加载
- (void)footer {
    self.page = 1;
    self.page ++;
    if (self.northChinaTableView) {
        self.url = [NSString stringWithFormat:@"http://app.api.autohome.com.cn/autov5.0.0/club/jingxuantopic-pm1-c218-p%ld-s30.json", self.page];
    } else if (self.centerChinaTableView) {
        self.url = [NSString stringWithFormat:@"http://app.api.autohome.com.cn/autov5.0.0/club/jingxuantopic-pm1-c220-p%ld-s30.json", self.page];
    } else if (self.eastChinaTableView) {
        self.url = [NSString stringWithFormat:@"http://app.api.autohome.com.cn/autov5.0.0/club/jingxuantopic-pm1-c219-p%ld-s30.json", self.page];
    }
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:self.url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = responseObject;
        for (NSDictionary *temp in dic[@"result"][@"list"]) {
            SHModel *model = [[SHModel alloc] init];
            [model setValuesForKeysWithDictionary:temp];
            [self.northChinaArr addObject:model];
            [self.centerChinaArr addObject:model];
            [self.eastChinaArr addObject:model];
            [model release];
        }
        [self.northChinaTableView reloadData];
        [self.northChinaTableView.footer endRefreshing];
        [self.centerChinaTableView reloadData];
        [self.centerChinaTableView.footer endRefreshing];
        [self.eastChinaTableView reloadData];
        [self.centerChinaTableView.footer endRefreshing];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}

#pragma mark - collectionView
- (void) createBottomCollectionView{
    UICollectionViewFlowLayout *flowLayout = [[[UICollectionViewFlowLayout alloc] init] autorelease];
        // 设置等屏大
    flowLayout.itemSize = CGSizeMake(WIDTH, HEIGHT - 35);
    flowLayout.minimumLineSpacing = 0;
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 35, WIDTH, HEIGHT - 35) collectionViewLayout:flowLayout];
    [self.view addSubview:self.collectionView];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    self.collectionView.pagingEnabled = YES;
        
        // 注册
    [self.collectionView registerClass:[SHForumCollectionCell class] forCellWithReuseIdentifier:@"collection"];
    [self.view addSubview:self.collectionView];
    [_collectionView release];
    self.collectionView.pagingEnabled = YES;
    
}

#pragma mark --northChinaTableView;
- (UITableView *)northChinaTableView {
    if (!_northChinaTableView) {
        self.northChinaTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 20, WIDTH, HEIGHT) style:UITableViewStylePlain];
        self.northChinaTableView.dataSource = self;
        self.northChinaTableView.delegate = self;
        self.northChinaTableView.rowHeight = 120;
        self.northChinaTableView.tag = 101;
    }
    return _northChinaTableView;
}

#pragma mark --centerChinaTableView
- (UITableView *)centerChinaTableView {
    if (!_centerChinaTableView) {
        self.centerChinaTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 20, WIDTH, HEIGHT) style:UITableViewStylePlain];
        self.centerChinaTableView.dataSource = self;
        self.centerChinaTableView.delegate = self;
        self.centerChinaTableView.rowHeight = 120;
        self.centerChinaTableView.tag = 102;
    }
    return _centerChinaTableView;
}
#pragma mark --eastChinaTableView
- (UITableView *)eastChinaTableView {
    if (!_eastChinaTableView) {
        self.eastChinaTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 20, WIDTH, HEIGHT) style:UITableViewStylePlain];
        self.eastChinaTableView.dataSource = self;
        self.eastChinaTableView.delegate = self;
        self.eastChinaTableView.rowHeight = 120;
    }
    return _eastChinaTableView;
}
#pragma mark northChinaData
- (void)createNorthChinaData {
    [SHNetWorkingTool getNetWorking:@"http://app.api.autohome.com.cn/autov5.0.0/club/jingxuantopic-pm1-c218-p1-s30.json" block:^(id result) {
        NSDictionary *dic = result;
        self.northChinaArr = [NSMutableArray array];
        self.northChinaArr = [SHModel baseModelByArr:dic[@"result"][@"list"]];
        [self.hud removeFromSuperview];
        [self.northChinaTableView reloadData];
    }];
    [self createCenterChinaData];
}
//http://app.api.autohome.com.cn/autov5.0.0/club/jingxuantopic-pm1-c224-p1-s30.json
- (void)createCenterChinaData {
    [SHNetWorkingTool getNetWorking:@"http://app.api.autohome.com.cn/autov5.0.0/club/jingxuantopic-pm1-c220-p1-s30.json" block:^(id result) {
        NSDictionary *dic = result;
        self.centerChinaArr = [NSMutableArray array];
        self.centerChinaArr = [SHModel baseModelByArr:dic[@"result"][@"list"]];
        [self.centerChinaTableView reloadData];
        [self.centerChinaTableView.header endRefreshing];
    }];
    [self createEastChinaData];
}
- (void)createEastChinaData {
    [SHNetWorkingTool getNetWorking:@"http://app.api.autohome.com.cn/autov5.0.0/club/jingxuantopic-pm1-c219-p1-s30.json" block:^(id result) {
        NSDictionary *dic = result;
        self.eastChinaArr = [NSMutableArray array];
        self.eastChinaArr = [SHModel baseModelByArr:dic[@"result"][@"list"]];
        [self.eastChinaTableView reloadData];
        [self.eastChinaTableView.header endRefreshing];
    }];
    

}
#pragma mark collectionView方法
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView == self.collectionView) {
        SHForumCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"collection" forIndexPath:indexPath];
        if (indexPath.row == 0) {
            [cell.onceView addSubview:self.northChinaTableView];
        }else if(indexPath.row == 1) {
            [cell.onceView addSubview:self.centerChinaTableView];
        }else {
            [cell.onceView addSubview:self.eastChinaTableView];
        }
        
        return cell;

    } else {
        SHHeaderCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"headerCollection" forIndexPath:indexPath];
        for (NSInteger i = 0; i < 3; i++) {
            cell.nowView.hidden = YES;
            cell.label.textColor = [UIColor blackColor];
        }
        if (indexPath.row == self.selectCount) {
            cell.nowView.hidden = NO;
            cell.label.textColor = [UIColor redColor];
        }
        if (indexPath.row == 0) {
            cell.label.text = @"华北";
            
        } else if (indexPath.row == 1) {
            cell.label.text = @"华中";
            
        } else {
            cell.label.text = @"华南";
            
        }
        return cell;
    }
   }

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView == self.headCollectionView) {
        self.selectCount = indexPath.row;
        self.collectionView.contentOffset = CGPointMake(WIDTH * self.selectCount, 0);
        [self.headCollectionView reloadData];
    }
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView == self.collectionView) {
        self.selectCount = self.collectionView.contentOffset.x / WIDTH;
        for (NSInteger i = 0; i < 4; i++) {
            if (self.collectionView.contentOffset.x == WIDTH * i) {
                self.headCollectionView.contentOffset = CGPointMake(0, 0);
            }
        }
    }
    [self.headCollectionView reloadData];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
   
         return 3;
   }

#pragma mark tableView方法
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.northChinaTableView) {
        static NSString *reuse = @"reuse";
        SHNewslistCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
        if (!cell) {
            cell = [[[SHNewslistCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuse] autorelease];
        }
        SHModel *model = self.northChinaArr[indexPath.row];
        [cell.leftImageView sd_setImageWithURL:[NSURL URLWithString:model.smallpic] placeholderImage:PLACEPICTURE];
        cell.titleLabel.text = model.title;
        cell.titleLabel.numberOfLines = 2;
        [cell.titleLabel sizeToFit];
        cell.titleLabel.textColor = TEXTCOLOR;
        
        cell.timeLabel.text = model.time;
        cell.timeLabel.font = [UIFont systemFontOfSize:10];
        
        
        cell.replycountLabel.text = [NSString stringWithFormat:@"%@%@", model.replycounts, @"评论"];
        cell.replycountLabel.font = [UIFont systemFontOfSize:10];
        cell.replycountLabel.textAlignment = NSTextAlignmentRight;
        cell.replycountLabel.textColor = TEXTCOLOR;

        return cell;

    } else if (tableView == self.centerChinaTableView) {
        static NSString *reuse = @"center";
        SHNewslistCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
        if (!cell) {
            cell = [[[SHNewslistCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuse] autorelease];
        }
        SHModel *model = self.centerChinaArr[indexPath.row];
      
        [cell.leftImageView sd_setImageWithURL:[NSURL URLWithString:model.smallpic] placeholderImage:PLACEPICTURE];
        cell.titleLabel.text = model.title;
        cell.titleLabel.numberOfLines = 2;
        [cell.titleLabel sizeToFit];
        cell.titleLabel.textColor = TEXTCOLOR;
        cell.timeLabel.text = model.time;
        cell.timeLabel.font = [UIFont systemFontOfSize:10];
        
        cell.replycountLabel.text = [NSString stringWithFormat:@"%@%@", model.replycounts, @"评论"];
        cell.replycountLabel.font = [UIFont systemFontOfSize:10];
        cell.replycountLabel.textAlignment = NSTextAlignmentRight;
        cell.replycountLabel.textColor = TEXTCOLOR;
        return cell;
    }  else {
        static NSString *reuse = @"east";
        SHNewslistCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
        if (!cell) {
            cell = [[[SHNewslistCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuse] autorelease];
        }
        SHModel *model = self.eastChinaArr[indexPath.row];
        [cell.leftImageView sd_setImageWithURL:[NSURL URLWithString:model.smallpic] placeholderImage:PLACEPICTURE];
        cell.titleLabel.text = model.title;
        cell.titleLabel.numberOfLines = 2;
        [cell.titleLabel sizeToFit];
        cell.titleLabel.textColor = TEXTCOLOR;
        
        cell.timeLabel.text = model.time;
        cell.timeLabel.font = [UIFont systemFontOfSize:10];
        
        cell.replycountLabel.text = [NSString stringWithFormat:@"%@%@", model.replycounts, @"评论"];
        cell.replycountLabel.font = [UIFont systemFontOfSize:10];
        cell.replycountLabel.textAlignment = NSTextAlignmentRight;
        cell.replycountLabel.textColor = TEXTCOLOR;
        return cell;

        
    }
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.northChinaTableView) {
        return self.northChinaArr.count;
    } else if (tableView == self.centerChinaTableView) {
        return self.centerChinaArr.count;
    } else {
        return self.eastChinaArr.count;
    }
}



- (void)createHud
{
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.hud.labelText = @"正在加载...";
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.northChinaTableView) {
        SHDetailViewController *detail = [[SHDetailViewController alloc] init];
        [self.navigationController pushViewController:detail animated:YES];
        
        SHModel *model = self.northChinaArr[indexPath.row];
        NSString *webUrl = [NSString stringWithFormat:@"http://comm.app.api.autohome.com.cn/static/sharejump.html?p=1&pm=1&go=1&cont=4&ourl=http://forum.app.autohome.com.cn/autov5.0.0/forum/club/topicsharedcontent-t%@-o0.html", model.topicid];
        detail.webStr = webUrl;
        [detail release];
       
    } else if (tableView == self.centerChinaTableView) {
        SHDetailViewController *detail = [[SHDetailViewController alloc] init];
        [self.navigationController pushViewController:detail animated:YES];
        SHModel *model = self.centerChinaArr[indexPath.row];
        NSString *webUrl = [NSString stringWithFormat:@"http://comm.app.api.autohome.com.cn/static/sharejump.html?p=1&pm=1&go=1&cont=4&ourl=http://forum.app.autohome.com.cn/autov5.0.0/forum/club/topicsharedcontent-t%@-o0.html", model.topicid];
        detail.webStr = webUrl;
        [detail release];
    } else {
        SHDetailViewController *detail = [[SHDetailViewController alloc] init];
        [self.navigationController pushViewController:detail animated:YES];
        SHModel *model = self.eastChinaArr[indexPath.row];
        NSString *webUrl = [NSString stringWithFormat:@"http://comm.app.api.autohome.com.cn/static/sharejump.html?p=1&pm=1&go=1&cont=4&ourl=http://forum.app.autohome.com.cn/autov5.0.0/forum/club/topicsharedcontent-t%@-o0.html", model.topicid];
        detail.webStr = webUrl;
        [detail release];
    }
   
//    563c383667e58e4ed7000fba 友盟Appkey
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
